package com.jse.util.concurrent.new1.collection;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.junit.Test;

/**
 * 阻塞队列接口方法
 *  	抛出异常 特殊值 阻塞 超时 
	插入 add(e) offer(e) put(e) offer(e, time, unit) 
	移除 remove() poll() take() poll(time, unit) 
	检查 element() peek() 不可用 不可用 

	参考生产者消费者测试用例：
	test.java.util.concurrent.BlockingQueue.ProducerConsumerLoops
 * @author Administrator
 *
 */
public class ArrayBlockingQueueTest {
	ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(1);
	
	/**
	 * 生产者消费者测试
	 */
	@Test
	public void testAdd() {
		ExecutorService executor = Executors.newCachedThreadPool();
		for (int i = 0; i < 2; i++) {
			executor.execute(new IncrementTask(i));
		}
		
		for (int i = 0; i < 3; i++) {
			executor.execute(new DecreaseTask(i));
		}
	}
	
	class IncrementTask implements Runnable {
		public int i;
		
		public IncrementTask(int i) {
			this.i = i;
		}
		
		@Override
		public void run() {
//			queue.add(i);//超出就抛出异常
//			System.out.println(queue.offer(i));//可以看到是否添加成功
			
			try {
				queue.put(i);
//				System.out.println(queue.size());
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	} 
	class DecreaseTask implements Runnable {
		public int j;
		
		public DecreaseTask(int j) {
			this.j = j;
		}
		
		@Override
		public void run() {
			System.out.println(queue.size());
//			queue.poll();
			try {
				queue.take();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println(queue.size());
		}
	}
}
